import wx from 'weixin-js-sdk'
import api from '../../http/api'
// import CryptoJS from 'crypto-js'

export {
  tabChange,
  countDown,
  tow,
  setAddressInfoStorage,
  removeAddressInfoStorage,
  requireShare,
  insertPvUv,
  getIp,
  isPC,
  encrypt,
  decrypt,
  ternaryOperator,
  isArrayFn
}

/**
 * tab栏切换
 * @param val {Number} 要切换的tabbar栏下标
 * @returns {string}
 */
const tabChange = (val) => {
  let path = '';
  switch (val) {
    case 0:
      path = '/index/web/information';
      break;
    case 1:
      path = '/index/web/activities';
      break;
    case 2:
      path = '/index';
      break;
    case 3:
      path = '/index/web/service';
      break;
    case 4:
      path = '/index/web/center';
      break;
  }

  return path;
};

/**
 * 满十过滤
 * @param n
 * @returns {string}
 */
const tow = (n) => {
  return n >= 0 && n < 10 ? '0' + n : '' + n;
}

/**
 * 时间转化
 * @param time 2019/4/20  截止时间
 * @param isDay 是否不转换天数，默认转换(即不传入)
 * @returns {{day, hour, minute, second}}
 */
const countDown = (time,isDay) => {
  var data = '';//返回对象
  let oDate = new Date();//获取日期对象
  let oldTime = oDate.getTime();//现在距离1970年的毫秒数
  let newDate = new Date(time);
  let newTime = newDate.getTime();//2019年距离1970年的毫秒数
  let second = Math.floor((newTime - oldTime) / 1000);//未来时间距离现在的秒数
  let day = Math.floor(second / 86400);//整数部分代表的是天；一天有24*60*60=86400秒 ；
  (isDay && isDay != 'HH:MM:SS') ? '' : second = second % 86400;//余数代表剩下的秒数；
  let hour = Math.floor(second / 3600);//整数部分代表小时；
  second %= 3600; //余数代表 剩下的秒数；
  let minute = Math.floor(second / 60);
  second %= 60;

  if(isDay == 'HH:MM:SS') {
    data = tow(hour)+':'+tow(minute)+':'+tow(second)
  } else {
    data = {
      day:tow(day),
      hour:tow(hour),
      minute:tow(minute),
      second:tow(second),
    }
  }
  return data
}

/**
 * 设置localStorage
 * @param item
 */
const setAddressInfoStorage = item => {
  window.localStorage.setItem('addressInfoId',item.id)
  window.localStorage.setItem('addressInfoName',item.name)
  window.localStorage.setItem('addressInfoTel',item.tel)
  window.localStorage.setItem('addressInfoProvince',item.province)
  window.localStorage.setItem('addressInfoCity',item.city)
  window.localStorage.setItem('addressInfoCounty',item.county)
  window.localStorage.setItem('addressInfoAreaCode',item.areaCode)
  window.localStorage.setItem('addressInfoAddressDetail',item.addressDetail)
  window.localStorage.setItem('addressInfoIsDefault',item.isDefault)
}

/**
 * 清除个人信息localStorage
 */
const removeAddressInfoStorage = () => {
  window.localStorage.removeItem('addressInfoId')
  window.localStorage.removeItem('addressInfoName')
  window.localStorage.removeItem('addressInfoTel')
  window.localStorage.removeItem('addressInfoProvince')
  window.localStorage.removeItem('addressInfoCity')
  window.localStorage.removeItem('addressInfoCounty')
  window.localStorage.removeItem('addressInfoAreaCode')
  window.localStorage.removeItem('addressInfoAddressDetail')
  window.localStorage.removeItem('addressInfoIsDefault')
}

/**
 * 微信分享
 * @param data 分享数据
 * @param other
 * @param callback 回调
 * @param type 差异化参数 0.分享文章，1.分享视频，2.分享领礼品，3.分享活动页
 */
const requireShare = (data, other, callback, type) => {
  // 分享成功回调接口参数
  let requestData = {}

  if(type == 0) {
    requestData = { // 分享文章专区
      news_id: other.id
    }
  } else if(type == 1){
    requestData = {  // 分享视频专区
      vlog_id: other.id
    }
  } else if(type == 3) {
    requestData = {  // 分享活动专区
      activity_id: other.id
    }
  }

  wx.config({
    debug: false,
    appId: data.appId,
    timestamp: data.timestamp,
    nonceStr: data.nonceStr,
    signature: data.signature,
    jsApiList: [
      "onMenuShareTimeline",
      "onMenuShareAppMessage"
    ]
  });

  //微信分享
  wx.ready(function () {
    //分享到朋友圈
    wx.onMenuShareTimeline({
      title: data.title,
      link: data.link,
      imgUrl: data.imgUrl,
      success: function () {

        if(other.callback){
          $.post(api.points, requestData,(res) => {
          });
        }

        $.post(api.shareNewInserUser, requestData,(res) => {
          callback(res)
        });

        if(type == 3) { // 分享领礼品
          $.post(api.shareSign, {share: 1 }, (res) => {
            callback(res)
          });
        }
      }
    });

    //分享到朋友
    wx.onMenuShareAppMessage({
      title: data.title,
      desc: data.desc,
      link: data.link,
      imgUrl: data.imgUrl,
      type: 'link',
      dataUrl: '',
      success: function () {

        // 文章点赞
        if(other.callback){
          $.post(api.points, requestData,(res) => {
          });
        }
        // 分享领礼品
        if(type == 3) {
          $.post(api.shareSign, {share: 1 }, (res) => {
            callback(res)
          });
        }
      },
      cancel: function () {
      }
    });
  });
}

/**
 * PV/UV统计
 * @param url
 * @param type
 */
const insertPvUv = (url,type,product_id) => {
  if(localStorage.getItem('userIp')){
    if(localStorage.getItem(url)){
      $.post(api.InsertPv,{url:url,type:type},res => {
        $.post(api.InsertPvRecord,{url:url,type:type,product_id:product_id},res => {})
      })
    }else{
      localStorage.setItem(url,url)
      $.post(api.InsertPv,{url:url,type:type},res => {
        $.post(api.InsertPvRecord,{url:url,type:type,product_id:product_id},res => {})
      })
      $.post(api.InsertUv,{url:url,type:type},res => {})
    }
  }else{
    getIp()
    localStorage.setItem(url,url)
    $.post(api.InsertPv,{url:url,type:type},res => {
      $.post(api.InsertPvRecord,{url:url,type:type,product_id:product_id},res => {})
    })
    $.post(api.InsertUv,{url:url,type:type},res => {})
    $.post(api.InsertAllUv,(res) => {})
  }
}

/**
 * 获取ip
 */
const getIp = () => {
  //当日23:59:59时间戳
  let time = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1).getTime()
  $.post(api.getIp,(res) => {
    if(res.result == 200){
      localStorage.setItem('userIp',res.content.ip)
      localStorage.setItem('saveIpTime',time)
    }
  })
}

/**
 * 判断是否是PC打开
 * @returns {boolean}
 */
const isPC = () => {
  const userAgentInfo = navigator.userAgent;
  const Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
  let flag = true;
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
}

/**
 * 加密（需要先加载lib/aes/aes.min.js文件）
 */
const encrypt = (word) => {
  // let key = CryptoJS.enc.Utf8.parse("46cc793c53dc451b"); // 十六位十六进制数
  // let srcs = CryptoJS.enc.Utf8.parse(word);
  // let encrypted = CryptoJS.AES.encrypt(srcs, key, {
  //   mode: CryptoJS.mode.ECB,
  //   padding: CryptoJS.pad.Pkcs7
  // });
  // return encrypted.toString();
}
/**
 * 解密
 */
const decrypt = (word) => {
  // let key = CryptoJS.enc.Utf8.parse("46cc793c53dc451b");
  // let decrypt = CryptoJS.AES.decrypt(word, key, {
  //   mode: CryptoJS.mode.ECB,
  //   padding: CryptoJS.pad.Pkcs7
  // });
  // return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

/**
 * 三目运算符
 * @param val1
 * @param val2
 */
const ternaryOperator = (val1, val2) => val1 ? val1 : val2

/**
 * 是否是数组
 * @param {Object} value
 */
const isArrayFn = (value) => {
  // 首先判断浏览器是否支持Array.isArray这个方法
  if (typeof Array.isArray === "function") {
    return Array.isArray(value);
  }else{
    return Object.prototype.toString.call(value) === "[object Array]";
  }
}

